// pages/user/user.js
import { Address } from './addAddress-model.js';

const app = getApp()
const $address = new Address()

Page({

  /**
   * 页面的初始数据
   */
  data: {
      userInfo: {},
      dialogShow:false,
      threeArea:{
        provice:null,
        city: null,
        area: null
      },
      hasCity:true,
      hasArea:true,
      editAddress:null,
      editRegion:[],
      addressList:null,
      isShowPopup:false,
      tips:'',
      toggleWord:'新增',
      editId:'',
      loadDone:false,
      editStatusReset:false,
      type:'',
      orderId:'',
      addressId:''
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log(options)
    let that = this
    let userInfo = wx.getStorageSync('userInfo')
    wx.showLoading({
        title: '加载中',
    })
    // 判断是否是从选择地址过来的
    if(options.type){
        this.setData({
            userInfo: userInfo,
            type: options.type,
            orderId: options.orderId,
            addressId: options.addressId
        })
    }else{
        this.setData({
            userInfo: userInfo
        })
    }
    let provice = {
            "data": {
                "pid": "0"
            }
        }
    
      // 获取省一级 pid 0
    $address.getThree(provice,res=>{
        if(res.status){
            that.setData({
                'threeArea.provice': res.data
            })
            wx.hideLoading()

        } else {
            wx.hideLoading()
            $address.showMyTip({ _this: this, title: "服务器错误" })
        }
    })

  },
  preventD(e){
      return;
  },
  // 省选择
  proviceChange(e){
    console.log(e.detail.value)
    let val = e.detail.value
    let provice = this.data.threeArea.provice[val]
    let that = this
    let params = {
        "data": {
            "pid": provice.id
        }
    }
    $address.getThree(params, res => {
        if (res.status) {
            that.setData({
                'threeArea.city': res.data,
                'editRegion[1]': '',
                'editRegion[2]': '',
            })
        }
    })
    this.setData({
        'editRegion[0]': {
            id: provice.pid,
            name: provice.name,
            index: val
        },
        hasCity: false,
        hasArea: true
        
    }) 
    if(this.data.toggleWord == '编辑'){
        this.setData({
            'editAddress.detailedAddress': '',
            editStatusReset:true
        })
    }
  },
  // 市选择
  cityChange(e) {
      console.log(e.detail.value)
      let that = this
      let val = e.detail.value
      let city = this.data.threeArea.city[val]
      let params = {
            "data": {
                "pid": city.id
            }
      }
      $address.getThree(params, res => {
          if (res.status) {
              that.setData({
                  'threeArea.area': res.data,
                  'editRegion[2]': '',
                  
              })
          }
      })
      this.setData({
          'editRegion[1]': {
              id: city.pid,
              name: city.name,
              index: val
          },
          hasArea: false,
      })
      if (this.data.toggleWord == '编辑') {
          this.setData({
              'editAddress.detailedAddress': '',
                editStatusReset:true
          })
      }
  },
  // 区域选择
  areaChange(e) {
      console.log(e.detail.value)
      let val = e.detail.value
      let area = this.data.threeArea.area[val]
      
      this.setData({
          'editRegion[2]': {
              id: area.pid,
              name: area.name,
              index: val
          },          
      })
      if (this.data.toggleWord == '编辑') {
          this.setData({
              'editAddress.detailedAddress': '',
                editStatusReset:true
          })
      }
  },
  // 新增编辑地址
  formSubmit(e){
    console.log(e)
    let formdata = e.detail.value
    let that = this
    console.log(formdata)
    if (formdata.acceptName.trim() == ''){
        $address.showMyTip({ _this: this, title: "请输入收货人" })
    } else if (formdata.acceptName.length > 50) {
        $address.showMyTip({ _this: this, title: "收货人不超过50个字" })
    } else if (formdata.phone.trim() == '' || !/^((0\d{2,3}-\d{7,8})|(1[35847]\d{9}))$/.test(formdata.phone)){
        $address.showMyTip({ _this: this, title: "请输入正确的联系电话" })
    } else if (formdata.area == null || formdata.city == null || formdata.provice == null || formdata.area === '' || formdata.city === '' || formdata.provice === '') {
        $address.showMyTip({ _this: this, title: "请选择省市区县" })
    } else if (formdata.detail.trim() == ''){
        $address.showMyTip({ _this: this, title: "请输入详细地址" })   
    } else if (formdata.detail.length > 100) {
        $address.showMyTip({ _this: this, title: "收货地址不超过100个字" })
    }else{
        let data = this.data
        let threeArea = data.threeArea
        console.log(threeArea.provice[formdata.provice].name,
            threeArea.city[formdata.city].name, 
            threeArea.area[formdata.area].name)
        let PCA = threeArea.provice[formdata.provice].name + ' ' + threeArea.city[formdata.city].name + ' ' + threeArea.area[formdata.area].name + ' ' 
       
        let params = {
            data:{
                "userId": "" + data.userInfo.id,
                "province": "" + data.threeArea.provice[formdata.provice].id,
                "city": "" + data.threeArea.city[formdata.city].id,
                "area": "" +  data.threeArea.area[formdata.area].id,
                "detailedAddress": PCA+formdata.detail,
                "contacts": formdata.acceptName,
                "mobilePhone": formdata.phone
            }
        }

        console.log('params',params)
        wx.showModal({
            title: '提示',
            content: '确认保存吗？',
            success: function (res) {
                if (res.confirm) {
                    $address.addUserAddress(params,res3=>{
                        console.log('新增', res3)
                        let status = res3.status
                        if (status){
                            wx.showToast({
                                title: '新增成功',
                                icon: 'success',
                                duration: 1500,
                                success() {
                                    var pagelist = getCurrentPages();
                                    if (pagelist.length > 1) {
                                        //获取上一个页面实例对象
                                        var prePage = pagelist[pagelist.length - 2];
                                        //如果是订单详情跳转过来的
                                        if(data.type == 'sel'){
                                            prePage.onLoad({
                                                orderId: data.orderId,
                                                addressId: data.addressId
                                            });
                                        }else{
                                            prePage.onLoad();
                                        }
                                        wx.navigateBack({
                                            delta: 1
                                        })
                                        
                                    }
                                }
                            })
                        } else {
                            wx.hideLoading()
                            $address.showMyTip({ _this: that, title: "服务器错误" })
                        }
                    })
                } else if (res.cancel) {
                    console.log('用户点击取消')
                }
            }
        })
    }
  }
})